<?php

namespace JyUtils\Guard;

use JyUtils\Redis\Redis;
use JyUtils\Request\Request;
use JyUtils\Guard\GuardIp;
use JyUtils\Guard\GuardUa;

class Guard
{
  use GuardIp;
  use GuardUa;
  
  private static $config;
  private static $table_request_ip = 'Guard-request-ip';  // IP请求表
  private static $table_black_ua = 'Guard-black-ua';      // UA黑名单表
  private static $table_black_ip = 'Guard-black-ip';      // IP黑名单表
  
  public static function initRedis($config)
  {
    if (!isset($config['expire'])) {
      $config['expire'] = 86400;
    }
    Redis::_initialize($config);
  }
  
  /**
   * 开始守护
   *
   * @param array $config
   */
  public static function startGuard($config = [])
  {
    if (!isset($config['request_duration'])) {
      $config['request_duration'] = 10;
    }
    // ip限制，轻微
    if (!isset($config['light_ip_count'])) {
      $config['light_ip_count'] = 10;
    }
    if (!isset($config['light_ip_intercept'])) {
      $config['light_ip_intercept'] = true;
    }
    if (!isset($config['light_ip_black'])) {
      $config['light_ip_black'] = 0;
    }
    if (!isset($config['light_ip_black_intercept'])) {
      $config['light_ip_black_intercept'] = true;
    }
    
    // ip限制，严重
    if (!isset($config['strict_ip_count'])) {
      $config['strict_ip_count'] = 60;
    }
    if (!isset($config['strict_ip_intercept'])) {
      $config['strict_ip_intercept'] = true;
    }
    if (!isset($config['strict_ip_black'])) {
      $config['strict_ip_black'] = 300;
    }
    if (!isset($config['strict_ip_black_intercept'])) {
      $config['strict_ip_black_intercept'] = true;
    }
    
    self::$config = $config;
    
    // 保存配置
    self::saveConfig();
    
    // 开始守护IP请求
    self::startGuardIp();
    
    // 开始守护UA请求
    self::uaIsBlack();
  }
  
  public static function getConfig()
  {
    return Redis::get('_Guard_Config');
  }
  
  private static function saveConfig()
  {
    $config = self::$config;
    unset($config['host']);
    unset($config['port']);
    unset($config['expire']);
    unset($config['password']);
    unset($config['db']);
    unset($config['timeout']);
    Redis::set('_Guard_Config', $config);
  }
}
